import 'package:flutter/material.dart';
import '../../widget/LoadingWidget.dart';
import '../../common/ScreenAdaper.dart';
import 'package:dio/dio.dart';
import '../../config/Config.dart';
import '../../model/CateModel.dart';


class CategoryPage extends StatefulWidget {
  @override
  _CategoryPageState createState() => _CategoryPageState();
}

class _CategoryPageState extends State<CategoryPage> with AutomaticKeepAliveClientMixin{
  @override
  // TODO: implement wantKeepAlive
  bool get wantKeepAlive => true;

  int _selectIndex = 0;
  // 分类信息
  List _classData = [];
  List _listData = [];
  // ignore: must_call_super
  void initState(){
    super.initState();
    _getClassDate();

    //监听滚动条事件
    _scrollController.addListener(() {
      print(_scrollController.position.pixels); //获取滚动条下拉的距离
      print(_scrollController.position.maxScrollExtent); //获取整个页面的高度
      if (_scrollController.position.pixels >
          _scrollController.position.maxScrollExtent - 40) {
        this._getListData(_typeId);
      }
    });
  }

  // 滚动条
  ScrollController _scrollController = new ScrollController();
  // 当前栏目ID
  int _typeId = 1;
  int _page = 1;
  bool hasMore = true; //判断有没有数据

  @override
  Widget build(BuildContext context) {
    S.init(context);
    // 左侧宽度
    var leftWidth=S.getScreenWidth()/4;
    //右侧每一项宽度=（总宽度-左侧宽度-GridView外侧元素左右的Padding值-GridView中间的间距）/3
    var rightItemWidth=(S.getScreenWidth()-leftWidth-20-20)/3;
    //获取计算后的宽度
    rightItemWidth=S.width(rightItemWidth);
    //获取计算后的高度
    var rightItemHeight=rightItemWidth+S.height(28);

    // 左侧导航
    Widget _leftWidget(){
      if(this._classData.length > 0){
        return ListView.builder(
          itemCount: this._classData.length,
          itemBuilder: (BuildContext context, int index) {
            return Column(
              children: <Widget>[
                InkWell(
                  onTap: (){
                    setState(() {
                      _selectIndex= index;
                      this._page = 1;
                      this._listData = [];
                      this._getListData(this._classData[index]["Id"]);
                      this._typeId = this._classData[index]["Id"];
                    });
                  },
                  child: Container(
                    padding: EdgeInsets.only(top: S.height(22)),
                    width: double.infinity,
                    height: S.height(80),
                    child: Text("${_classData[index]["Name"]}",textAlign: TextAlign.center),
                    color: _selectIndex==index?Color.fromRGBO(240, 246, 246, 0.9):Colors.white,
                  ),
                ),
                Divider(height: 1,)
              ],
            );
          },
        );
      } else {
        return LoadingWidget();
      }
    }

    // 右侧组件
    Widget _rightWidget(){
      if(this._listData.length > 0){
        return RefreshIndicator(
          onRefresh: _onRefresh,
          child: ListView.builder(
            controller: _scrollController,// 监听滚动条事件
            itemCount: _listData.length,
            itemBuilder: (context,index){
              if(index == _listData.length - 1){ // 列表渲染到最后一条,出现加载圈圈，数据展示完显示---底线
                if(hasMore == false){ // 没有数据的时候
                  return Center(
                    child: Text("--------我是有底线的--------"),
                  );
                } else{
                  return Column(
                    children: [
                      Container(
                        child: GestureDetector(
                          child: Row(
                            children: <Widget>[
                              Container(
                                width: S.width(180),
                                height: S.height(220),
                                child: Image.network("${_listData[index]["Image"]}", fit: BoxFit.cover),
                              ),
                              Expanded(
                                flex: 1,
                                child: Container(
                                  height: S.height(240),
                                  margin: EdgeInsets.only(left: 10),
                                  child: Column(
                                    crossAxisAlignment: CrossAxisAlignment.start,
                                    children: <Widget>[
                                      Text("${_listData[index]["Name"]}", maxLines: 1,
                                        overflow: TextOverflow.ellipsis,
                                        style: TextStyle(fontSize: S.size(30),
                                            fontWeight: FontWeight.bold),),
                                      Container(
                                        padding: EdgeInsets.only(top: 1, bottom: 1),
                                        child: Text("作者：${_listData[index]["Author"]}", maxLines: 1,
                                            overflow: TextOverflow.ellipsis,
                                            style: TextStyle(fontSize: S.size(28),
                                                color: Colors.black54)),
                                      ),
                                      Text("${_listData[index]["Info"]}", maxLines: 5,
                                        overflow: TextOverflow.ellipsis,),
                                    ],
                                  ),
                                ),
                              ),
                            ],
                          ),
                          onTap: () {
                            Navigator.pushNamed(context, "/book",arguments:{"bookId":_listData[index]["BookId"]});
                          },
                        ),
                      ),
                      Divider(height: 1,),
                      LoadingWidget()
                    ],
                  );
                }
              } else {
                return Column(
                  children: [
                    Container(
                      child: GestureDetector(
                        child: Row(
                          children: <Widget>[
                            Container(
                              width: S.width(180),
                              height: S.height(220),
                              child: Image.network("${_listData[index]["Image"]}", fit: BoxFit.cover),
                            ),
                            Expanded(
                              flex: 1,
                              child: Container(
                                height: S.height(240),
                                margin: EdgeInsets.only(left: 10),
                                child: Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: <Widget>[
                                    Text("${_listData[index]["Name"]}", maxLines: 1,
                                      overflow: TextOverflow.ellipsis,
                                      style: TextStyle(fontSize: S.size(30),
                                          fontWeight: FontWeight.bold),),
                                    Container(
                                      padding: EdgeInsets.only(top: 1, bottom: 1),
                                      child: Text("作者：${_listData[index]["Author"]}", maxLines: 1,
                                          overflow: TextOverflow.ellipsis,
                                          style: TextStyle(fontSize: S.size(28),
                                              color: Colors.black54)),
                                    ),
                                    Text("${_listData[index]["Info"]}", maxLines: 5,
                                      overflow: TextOverflow.ellipsis,),
                                  ],
                                ),
                              ),
                            ),
                          ],
                        ),
                        onTap: () {
                          Navigator.pushNamed(context, "/book",arguments:{"bookId":_listData[index]["BookId"]});
                        },
                      ),
                    ),
                    Divider(height: 1,),
                  ],
                );
              }
            },
          ),
        );
      } else {
        return LoadingWidget();
      }
    }


    return Row(
      children: <Widget>[
        Container(
          width: leftWidth,
          height: double.infinity,
          child: _leftWidget(),
        ),
        Expanded(
          flex: 1,
          child: Container(
            padding: EdgeInsets.all(10),
            height: double.infinity,
            color: Color.fromRGBO(240, 246, 246, 0.9),
            child: _rightWidget(),
          ),
        )
      ],
    );
  }

  //=================================================

  // 获取分类
  _getClassDate() async{
    if(hasMore){
      var apiUrl = "${Config.domain}api/book/class";
      Response result=await Dio().get(apiUrl);
      var list=result.data;
      setState(() {
        this._classData = list;
        this._typeId = _classData[0]["Id"];
      });
      _getListData(_typeId);
    }
  }
  // 获取分类下的列表
  _getListData(id) async{
    var apiUrl = "${Config.domain}api/book/list?typeid=${id}&page=${_page}";
    print(apiUrl);
    Response result=await Dio().get(apiUrl);
    var list=result.data;
    if(list["code"] == 1){
      setState(() {
        this._listData.addAll(list["data"]);
        this._page++;
      });
    }
  }

  //上拉刷新
  Future<void> _onRefresh() async {
    await Future.delayed(Duration(milliseconds: 2000), () {
      _getListData(_typeId);
    });
  }

}